package ee.maoinvest.frontend.controller.command.substationcommands;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ee.maoinvest.backend.model.data.ElectricityMeter;
import ee.maoinvest.backend.model.data.Substation;
import ee.maoinvest.backend.services.ElectricityMeterService;
import ee.maoinvest.backend.services.SubstationService;
import ee.maoinvest.backend.services.implementations.ElectricityMeterServiceImpl;
import ee.maoinvest.backend.services.implementations.SubstationServiceImpl;
import ee.maoinvest.frontend.controller.command.Command;
import ee.maoinvest.frontend.controller.formstringdataconverters.substationforms.DeleteSubstationFormConverter;
import ee.maoinvest.frontend.controller.requestprocessors.SubstationFormsRequestProcessor;

public class FillDeleteSubstationFormConverterWithInitialData implements Command
{
	private int operationResult = 0;
	private final int OPERATION_SUCCESSFUL = 1;
	private final int OPERATION_UNSUCCESSFUL = 0;
	private final int ID_PARSE_ERROR_IDENTIFICATOR = -1;
	
	@Override
	public int executeCommand(HttpServletRequest request,
			HttpServletResponse response) 
	{
		SubstationFormsRequestProcessor substationFormsRequestProcessor = 
				new SubstationFormsRequestProcessor();
		DeleteSubstationFormConverter deleteSubstationFormConverter = null;
		List<ElectricityMeter> listOfAllSubstationMainElectricityMetersConnectedWithSubstation = null;
		Substation substationBeingDeleted = null;
		int substationIDToDelete = substationFormsRequestProcessor.getSubstationIDToDelete(request);
		
		
		if (substationIDToDelete != ID_PARSE_ERROR_IDENTIFICATOR)
		{
			ElectricityMeterService electricityMeterServiceImpl = new ElectricityMeterServiceImpl();
			SubstationService substationServiceImpl = new SubstationServiceImpl();
			deleteSubstationFormConverter = new DeleteSubstationFormConverter();
			
			listOfAllSubstationMainElectricityMetersConnectedWithSubstation = 
					electricityMeterServiceImpl.getSubstationMainElectricityMetersConnectedWithSubstation(substationIDToDelete);
			substationBeingDeleted = substationServiceImpl.getSubstationById(substationIDToDelete);
			
			deleteSubstationFormConverter.fillWithInitialData(substationBeingDeleted, 
					listOfAllSubstationMainElectricityMetersConnectedWithSubstation);
			request.setAttribute("deleteSubstationFormConverter", deleteSubstationFormConverter);
			
			HttpSession session = request.getSession();
			session.setAttribute("listOfAllSubstationMainElectricityMetersConnectedWithSubstation", 
					listOfAllSubstationMainElectricityMetersConnectedWithSubstation);
			session.setAttribute("substationBeingDeleted", substationBeingDeleted);
			operationResult = OPERATION_SUCCESSFUL;
			
		}
		else
		{
			operationResult = OPERATION_UNSUCCESSFUL;
		}
		
		return operationResult;
	}
}
